package project.main;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.Map;

import project.crawler.parser.UserParser;
import project.dbaccesslayer.MySQLAccessLayer;
import project.dbaccesslayer.Table_SO_Users;
import project.model.adt.User;

public class ParseUsers {

	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.out.println("Usage: ParseUsers <limit>");
			return;
		}
		if (!args[0].matches("\\d+")) {
			java.util.List<String> lines = Files.readAllLines(
					Paths.get("..", args[0]), Charset.defaultCharset());
			String str = "";
			for (String line : lines) {
				str += line;
			}
			User u = UserParser.parseUser(str);
			System.out.println(u);
			return;
		}
		int limit = Integer.parseInt(args[0]);

		Connection conn = MySQLAccessLayer.openConnectionToMySql();

		while (limit > 0) {
			Map<Long, String> map = Table_SO_Users.getUsersToParse(conn);
			System.out.println("Got " + map.size() + " users to parse.");

			if (map.isEmpty()) {
				break;
			}

			for (long userID : map.keySet()) {
				System.out.println("Parsing user " + userID);
				User u = UserParser.parseUser(map.get(userID));
				Table_SO_Users.saveUser(conn, u);
			}

			limit -= map.size();
		}

		System.out.println("Done.");

		conn.close();
	}

}
